/**
 * 
 */
var geocodeTimer;
var FTUserRouteLayer=null;
var distanceWidget=null;
var maxDistance=0;
var join=0;
var initPosFlag = new Boolean(false);
var initPos;
var initPosMarker;
var endPos;
var ruta=0;
var r1Id="--";
var r1LatLong="--";
var r2Id="--";
var r2LatLong="--";

var initFunction = function initialize() {
	//Get the user location via W3C standard
	var initialLocation = new google.maps.LatLng(42.846406, -2.667893);
	//Create the map
	createMap(initialLocation, "auto");
	
	setBlueStyle();
	
	distanceWidget = new DistanceWidget({
		map: map,
		distance: 50, // Starting distance in km.
		maxDistance: 2500, // Twitter has a max distance of 2500km.
		color: '#000000',
		activeColor: '#5599bb',
		sizerIcon: new google.maps.MarkerImage('components/com_socialroutes/images/resize-off.png'),
		activeSizerIcon: new google.maps.MarkerImage('components/com_socialroutes/images/resize.png')
	});
	
	google.maps.event.addListener(distanceWidget, 'active_changed', function() {
		if(!distanceWidget.get('active')){
			displayDistance(distanceWidget);
			displayFTRoutes(distanceWidget);
		}
	});
	
	google.maps.event.addListener(distanceWidget, 'dragend_changed', function() {
		if(distanceWidget.get('dragend')){
			displayPosition(distanceWidget);
			displayFTRoutes(distanceWidget);
		}
	});
	
	map.fitBounds(distanceWidget.get('bounds'));
	
	displayDistance(distanceWidget);
	displayPosition(distanceWidget);
	displayFTRoutes(distanceWidget);

	initialLocation = locateUser();
	
	
};

function displayDistance(widget) {
	var circleRadius = document.getElementById('circleRadius');
	circleRadius.value = widget.get('distance').toFixed(2);
	$('#circleRadiusText').html(circleRadius.value);
}

 function foundLocation(position)
 {

   var lat = position.coords.latitude;
   var longi = position.coords.longitude;
   
   alert('Found location: ' + lat + ', ' + longi);
 }
 function noLocation()
 {
   alert('Could not find location');
 }

function displayPosition(widget) {
	if (geocodeTimer) {
	    window.clearTimeout(geocodeTimer);
	}
	
	geocodeTimer = window.setTimeout(function() {
	    reverseGeocodePosition(widget);
	}, 200);
}

function reverseGeocodePosition(widget) {

  var pos = widget.get('position');
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({'latLng': pos}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[1]) {
    	  var keywords = document.getElementById('keywords');
    	  keywords.value= results[1].formatted_address;
    	  //alert (keywords.value);
    	  $('#keywordsText').html(keywords.value);
        return;
      }
    }
  });
}

function displayFTRoutes(widget){
	
	if (join==0){
	var radius = widget.get('distance').toFixed(2);
	
	var pos = widget.get('position');
	
	
	
	var distanceClause="";
	if(maxDistance!=0 && maxDistance){
		distanceClause="distance<"+maxDistance+" AND";
	}

	if(!FTUserRouteLayer){
		FTUserRouteLayer = new google.maps.FusionTablesLayer(323755,{
			query: "SELECT route FROM 323755 WHERE "+distanceClause+" ST_INTERSECTS(route,CIRCLE(LATLNG("+pos.lat()+","+pos.lng()+"),"+radius*1000+"))"
		});
	}
	else{
		FTUserRouteLayer.setOptions({
			query: "SELECT route FROM 323755 WHERE "+distanceClause+" ST_INTERSECTS(route,CIRCLE(LATLNG("+pos.lat()+","+pos.lng()+"),"+radius*1000+"))"
		});
	}
	
	}
	else{
		
		
		FTUserRouteLayer = new google.maps.FusionTablesLayer(323755,{
			query: "SELECT route FROM 323755"
		});
		
		
	}

	FTUserRouteLayer.setMap(map);
	
	google.maps.event.addListener(FTUserRouteLayer, 'click', joinRoutes );
	
}


function joinRoutes(table) {
	
	//Cargamos la Ruta que ha clickado
	
	//alert(table.row['description'].value);
	
	//Se obtiene la Id de la ruta selecionada
	
	if (join==1){
		
		if (ruta==0){
		
			r1Id=table.row['id'].value;
			r1LatLong=table.latLng;
			
			initPosMarker = new google.maps.Marker({
			    position: table.latLng,
			    map: map
			});
		
			initPos=table.latLng;
			ruta = 1;
			
		    document.getElementById('r1Id').value=r1Id;
			document.getElementById('r1LatLong').value=r1LatLong;
	
		}else if (ruta ==1){
		
		
			r2Id=table.row['id'].value;
			r2LatLong=table.latLng;
			
			initPosMarker = new google.maps.Marker({
			    position: table.latLng,
			    map: map
			});
		
			document.getElementById('r2Id').value=r2Id;
			document.getElementById('r2LatLong').value=r2LatLong;
	
			ruta = 0;
	}
	
}

}


function updateMaxDistance(input){
	if(isNumeric(input.value)){
		maxDistance=input.value;
		displayFTRoutes(distanceWidget);
	}
	else{
		input.value="";
	}
}

function isNumeric(sText)

{
	var ValidChars = "0123456789.";
	var IsNumber = true;
	var Char;

	for (i = 0; i < sText.length && IsNumber == true; i++) {
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
	return IsNumber;
}
